<template>
  <div class="warehouse-container">
    <div class="page-header">
      <h1>🏢 Warehouse Management</h1>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">Add Warehouse</el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchName"
        placeholder="Search by warehouse name"
        style="width: 300px; margin-right: 10px"
        clearable
        @clear="loadWarehouses"
      />
      <el-select
        v-model="searchStatus"
        placeholder="Select status"
        style="width: 200px; margin-right: 10px"
        clearable
        @change="loadWarehouses"
      >
        <el-option label="Active" value="active" />
        <el-option label="Inactive" value="inactive" />
        <el-option label="Maintenance" value="maintenance" />
      </el-select>
      <el-button type="primary" :icon="Search" @click="loadWarehouses">Search</el-button>
    </div>

    <!-- 仓库卡片 -->
    <div class="warehouse-grid" v-loading="loading">
      <el-card 
        v-for="warehouse in warehouses" 
        :key="warehouse.id" 
        class="warehouse-card" 
        shadow="hover"
        @click="goToDetail(warehouse.id)"
        style="cursor: pointer"
      >
        <template #header>
          <div class="card-header">
            <span class="warehouse-name">{{ warehouse.name }}</span>
            <el-tag :type="getStatusType(warehouse.status)">
              {{ getStatusText(warehouse.status) }}
            </el-tag>
          </div>
        </template>
        
        <div class="warehouse-info">
          <div class="info-item">
            <el-icon><Location /></el-icon>
            <span>{{ warehouse.location }}</span>
          </div>
          <div class="info-item">
            <el-icon><Box /></el-icon>
            <span>Capacity: {{ warehouse.capacity }} units</span>
          </div>
          
          <!-- 联系信息 -->
          <div class="contact-info">
            <div><strong>Manager:</strong> {{ warehouse.manager }}</div>
            <div><strong>Phone:</strong> {{ warehouse.phone || 'N/A' }}</div>
          </div>
        </div>
        
        <template #footer>
          <div class="card-footer" @click.stop>
            <el-button type="primary" :icon="Edit" size="small" @click.stop="handleEdit(warehouse)">
              Edit
            </el-button>
            <el-button type="danger" :icon="Delete" size="small" @click.stop="handleDelete(warehouse)">
              Delete
            </el-button>
          </div>
        </template>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && warehouses.length === 0" description="No warehouses found" />

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="Warehouse Name" required>
          <el-input v-model="form.name" placeholder="Please enter warehouse name" />
        </el-form-item>
        <el-form-item label="Location" required>
          <el-input v-model="form.location" placeholder="Please enter location" />
        </el-form-item>
        <el-form-item label="Capacity" required>
          <el-input-number v-model="form.capacity" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="Manager" required>
          <el-input v-model="form.manager" placeholder="Please enter manager name" />
        </el-form-item>
        <el-form-item label="Phone">
          <el-input v-model="form.phone" placeholder="Please enter phone number" />
        </el-form-item>
        <el-form-item label="Status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">Active</el-radio>
            <el-radio label="inactive">Inactive</el-radio>
            <el-radio label="maintenance">Maintenance</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Location, Box, Search } from '@element-plus/icons-vue';
import { warehouseAPI } from '@/api';

const router = useRouter();

const warehouses = ref([]);
const loading = ref(false);
const saving = ref(false);
const searchName = ref('');
const searchStatus = ref('');

const dialogVisible = ref(false);
const dialogTitle = ref('Add Warehouse');
const isEditMode = ref(false);
const editId = ref(null);

const form = ref({
  name: '',
  location: '',
  capacity: 100,
  manager: '',
  phone: '',
  status: 'active'
});

// 加载仓库列表
const loadWarehouses = async () => {
  loading.value = true;
  try {
    const params = {};
    if (searchName.value) {
      params.name = searchName.value;
    }
    if (searchStatus.value) {
      params.status = searchStatus.value;
    }
    
    const response = await warehouseAPI.getList(params);
    if (response.success) {
      warehouses.value = response.data.warehouses;
    }
  } catch (error) {
    console.error('Failed to load warehouses:', error);
    ElMessage.error('Failed to load warehouses');
  } finally {
    loading.value = false;
  }
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'inactive': 'info',
    'maintenance': 'warning'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'active': 'Active',
    'inactive': 'Inactive',
    'maintenance': 'Maintenance'
  };
  return textMap[status] || status;
};

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = 'Add Warehouse';
  isEditMode.value = false;
  editId.value = null;
  form.value = { 
    name: '', 
    location: '', 
    capacity: 100, 
    manager: '', 
    phone: '', 
    status: 'active' 
  };
  dialogVisible.value = true;
};

// 编辑仓库
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Warehouse';
  isEditMode.value = true;
  editId.value = row.id;
  form.value = { 
    name: row.name,
    location: row.location,
    capacity: row.capacity,
    manager: row.manager,
    phone: row.phone || '',
    status: row.status
  };
  dialogVisible.value = true;
};

// 保存仓库
const handleSave = async () => {
  // 验证必填字段
  if (!form.value.name || !form.value.location || !form.value.manager) {
    ElMessage.warning('Please fill in all required fields');
    return;
  }

  if (form.value.capacity === undefined || form.value.capacity === '') {
    ElMessage.warning('Please enter warehouse capacity');
    return;
  }

  saving.value = true;
  try {
    const data = {
      name: form.value.name,
      location: form.value.location,
      capacity: form.value.capacity,
      manager: form.value.manager,
      phone: form.value.phone || null,
      status: form.value.status
    };

    let response;
    if (isEditMode.value) {
      response = await warehouseAPI.update(editId.value, data);
    } else {
      response = await warehouseAPI.create(data);
    }

    if (response.success) {
      ElMessage.success(isEditMode.value ? 'Updated successfully' : 'Created successfully');
      dialogVisible.value = false;
      loadWarehouses();
    }
  } catch (error) {
    console.error('Failed to save warehouse:', error);
    // 错误消息已经在 API 拦截器中处理
  } finally {
    saving.value = false;
  }
};

// 删除仓库
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `Are you sure you want to delete "${row.name}"?`, 
    'Confirm', 
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await warehouseAPI.delete(row.id);
      if (response.success) {
        ElMessage.success(`"${row.name}" deleted successfully`);
        loadWarehouses();
      }
    } catch (error) {
      console.error('Failed to delete warehouse:', error);
      // 错误消息已经在 API 拦截器中处理
      ElMessage.error(error.response?.data?.message || error.message || 'Delete failed');
    }
  }).catch(() => {});
};

// 跳转到仓库详情
const goToDetail = (warehouseId) => {
  router.push(`/warehouse/${warehouseId}`);
};

// 组件挂载时加载数据
onMounted(() => {
  loadWarehouses();
});
</script>

<style scoped>
.warehouse-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.warehouse-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.warehouse-card {
  border-radius: 12px;
  transition: all 0.3s ease;
}

.warehouse-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.warehouse-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.warehouse-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #666;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.contact-info {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #666;
}

.contact-info div {
  margin-bottom: 5px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .warehouse-grid {
    grid-template-columns: 1fr;
  }
}
</style>

